import cv2
import os
import argparse


def extract_frames(video_path, output_folder, frame_interval=1, scale=1.0):
    """
    从MP4视频中提取帧并保存为图片

    参数:
        video_path: 输入视频文件路径
        output_folder: 输出文件夹路径
        frame_interval: 每隔多少帧提取一帧(默认为1，即每帧都提取)
        scale: 缩放比例(默认为1.0，不缩放)
    """
    # 创建输出文件夹
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)

    # 打开视频文件
    cap = cv2.VideoCapture(video_path)
    if not cap.isOpened():
        print("无法打开视频文件")
        return

    # 获取视频信息
    fps = cap.get(cv2.CAP_PROP_FPS)
    total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH) * scale)
    height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT) * scale)

    print(f"视频信息: {fps} FPS, 总帧数: {total_frames}, 分辨率: {width}x{height}")

    frame_count = 0
    saved_count = 0

    while True:
        ret, frame = cap.read()
        if not ret:
            break

        # 每隔frame_interval帧保存一次
        if frame_count % frame_interval == 0:
            # 缩放帧
            if scale != 1.0:
                frame = cv2.resize(frame, (width, height))

            # 保存帧为图片
            output_path = os.path.join(output_folder, f"frame_{saved_count:05d}.jpg")
            cv2.imwrite(output_path, frame)
            saved_count += 1

        frame_count += 1

    cap.release()
    print(f"完成! 共保存了 {saved_count} 帧到 {output_folder}")


if __name__ == "__main__":
    extract_frames(r"C:\Users\11314\Downloads\微信小游戏特效制作 (1).mp4", r'D:\wx_game\images\tx', 10)
